package com.naxiangfish.cn.naxiangfish;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.naxiangfish.cn.R;
import com.naxiangfish.cn.backface.BackCall;
import com.naxiangfish.cn.been.VerSionBeen;
import com.naxiangfish.cn.board.BoardCastUtils;
import com.naxiangfish.cn.constant.ConstantUtils;
import com.naxiangfish.cn.constant.UriContent;
import com.naxiangfish.cn.naxiangfish.view.BannerActivity;
import com.naxiangfish.cn.naxiangfish.view.NewBasicTextActivity;
import com.naxiangfish.cn.updata.ApkUtils;
import com.naxiangfish.cn.updata.Constants;
import com.naxiangfish.cn.updata.PatchUtils;
import com.naxiangfish.cn.updata.SignUtils;
import com.naxiangfish.cn.utils.DialogUtil;
import com.naxiangfish.cn.utils.GsonUtil;
import com.naxiangfish.cn.utils.SaveUtils;
import com.naxiangfish.cn.utils.ToastMake;
import com.naxiangfish.cn.weigit.CustomHorizontalProgresWithNum;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;

import okhttp3.Call;

public class MainActivity extends BaseActivity {
    private static final int INSTALLAPK = 101;
    private BoardCastUtils mCastUtils;
    private int index = 1;



    // 成功
    private static final int WHAT_SUCCESS = 1;

    // 本地安装的微博MD5不正确
    private static final int WHAT_FAIL_OLD_MD5 = -1;

    // 新生成的微博MD5不正确
    private static final int WHAT_FAIL_GEN_MD5 = -2;

    // 合成失败
    private static final int WHAT_FAIL_PATCH = -3;

    // 获取源文件失败
    private static final int WHAT_FAIL_GET_SOURCE = -4;

    // 未知错误
    private static final int WHAT_FAIL_UNKNOWN = -5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setWindShowStyle(ConstantUtils.LINEARSHOW);
        setContentViewShow(R.layout.activity_main);
        setTitleText("第1个界面");
    }

    public void save(View view) {
        SaveUtils.setString("赵航真帅", ConstantUtils.SAVECONSTANT);
        String string = SaveUtils.getString(ConstantUtils.SAVECONSTANT);
        System.out.println("string==" + string);
    }

    //        startActivity(new Intent(MainActivity.this, PayActivity.class));
    //显示加载状态
    //
    public void music(View view) {
        playMusic();
    }

    public void runanmition(View view) {
        startLoadingAnimation();
    }

    public void netcenct(View view) {
        boolean connected = isConnected();
        if (connected) {
            ToastMake.showToast("有网");
            System.out.println("有网");
        } else {
            ToastMake.showToast("无网");
            System.out.println("无网");
        }
    }

    public void alllistnet(View view) {
        //一般在OnCreat方法中创建监听
        if (mCastUtils == null) {
            mCastUtils = new BoardCastUtils();
            mCastUtils.netWork(this);
        }
        //记得注销
    }

    //复写父类的网络监听
    @Override
    public void onNetChange(int netMobile) {
        super.onNetChange(netMobile);
        switch (netMobile) {

            //无线网为1
            case ConstantUtils.LINEARSHOW:
                System.out.println("监听wifi移动网");
                break;

            //无网为-1
            case ConstantUtils.NETWORKNONE:

                System.out.println("监听无网");
                break;

            //移动网络0
            case ConstantUtils.RELEATSHOW:
                System.out.println("监听为移动网");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mCastUtils!=null) {
            mCastUtils.unRegistNetWork(MainActivity.this);
        }
    }

    //检查版本的更新
    public void update(View view) {
        chickeData();
    }

    /**
     * 获取软件版本号
     *
     * @return
     */
    private int getVersionCode() {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = MainActivity.this.getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取版本名字
     *
     * @return
     */
    private String getVersionName() {
        String versionName = "";
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionName = MainActivity.this.getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 检查版本并进行更新
     */
    private void chickeData() {
        final int versionCode = getVersionCode();
        String versionNme = getVersionName();
        System.out.println("versionNme=" + versionNme + "\n" + "versionCode=" + versionCode);
        startLoadingAnimation();
        if (isConnected()) {
            OkHttpUtils
                    .get()
                    .url(UriContent.updatauri)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            System.out.println("网络请求失败" + e.toString());
                            stopLoadingAnimation();
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            stopLoadingAnimation();

                            System.out.println("response" + response);
                            VerSionBeen been = GsonUtil.parseJsonToBean(response, VerSionBeen.class);
                            if (been == null) {
                                return;
                            }
                            //版本号大于当前的版本
                            if (been.getVersionCode() > versionCode) {
                                //进行升级
                                showUpDataDialog(been.getCancel(), been.getConfirm(), been.getTitle(), been.getIllustrate(), been.getUpuri());
                            } else {
                                DialogUtil.UpDataFanDialoge(MainActivity.this, new BackCall() {
                                    @Override
                                    public void deal(int which, Object... objects) {
                                        super.deal(which, objects);
                                    }
                                }).show();

                            }
                        }
                    });

        } else {
            ToastMake.showToast("网络连接失败，请检查网络");
        }
    }

    //展示对话框
    private void showUpDataDialog(String cancel, String confirm, String title, String illustrate, final String upuri) {
        Dialog dialog = DialogUtil.showInfoDialog(MainActivity.this, title, illustrate, cancel, confirm, new BackCall() {
            @Override
            public void deal(int which, Object... objects) {
                switch (which) {
                    case R.id.confirm:
                        if (isConnected()) {
                            UpData(upuri);
                        } else {
                            ToastMake.showToast("网络连接失败，请检查网络");
                        }
                        break;
                }
                super.deal(which, objects);
            }
        });
        dialog.show();

    }
    private void UpData(String upuri) {
        boolean permission = getSinglePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (!permission) {
            ToastMake.showToast("需要读取内存卡的权限");
            return;
        }
        //判断内存卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File file = new File(Environment.getExternalStorageDirectory() + "/" + getPackageName());
            if (!file.exists()){
                File dir = new File(Environment.getExternalStorageDirectory() + "/" + getPackageName());
                dir.mkdir();
            }
        }else {
            Toast.makeText(this, "sd卡不存在！", Toast.LENGTH_SHORT).show();
        }
        OkHttpUtils
                .get()
                .url(upuri)
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory() + "/" + getPackageName(), getResources().getText(R.string.app_name).toString()) {
                    private Dialog mDowFileDialog;
                    private CustomHorizontalProgresWithNum mHorizontalProgress;
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println("下载信息失败" + e.toString());
                    }
                    @Override
                    public void onResponse(File response, int id) {
                        String absolutePath = response.getAbsolutePath();
                        System.out.println("下载的文件路径是" + absolutePath);
                        /**
                         * 判断是否是8.0系统,是的话需要获取此权限，判断开没开，没开的话处理未知应用来源权限问题,否则直接安装
                         */
                        if (Build.VERSION.SDK_INT >= 26) {
                            boolean b = getPackageManager().canRequestPackageInstalls();
                            if (b) {
                                installApk(response);//安装应用的逻辑(写自己的就可以)
                            } else {
                                //请求安装未知应用来源的权限
                                getSinglePermission(Manifest.permission.REQUEST_INSTALL_PACKAGES);
                            }
                        } else {

                            installApk(response);
                        }

                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);

                        int mProgress = (int) (100 * progress);

                        if (mDowFileDialog == null) {
                            mDowFileDialog = DialogUtil.showDownFileDialog(MainActivity.this, new BackCall() {
                                @Override
                                public void deal(int which, Object... objects) {
                                    mHorizontalProgress = (CustomHorizontalProgresWithNum) objects[0];
                                    super.deal(which, objects);
                                }
                            });
                            mDowFileDialog.show();
                        }

                        mHorizontalProgress.setProgress(mProgress);
                        //当进度等于100的时吼，表示已经下载完成了
                        if (mProgress == 100) {
                            mDowFileDialog.hide();
                            System.out.println("下载完成了");
                        }
                    }
                });
    }

    //安装Apk文件
    private void installApk(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri =
                    FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        startActivityForResult(intent, INSTALLAPK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INSTALLAPK) {
            switch (resultCode) {

                //同意安装
                case Activity.RESULT_OK:

                    break;
                //取消安装
                case Activity.RESULT_CANCELED:

                    break;
            }

        }
    }

    public void bsdiff(View view){

        OkHttpUtils
                .get()
                .url(UriContent.upDataPatch)
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory() + "/" + getPackageName(),"NaXiang.patch") {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(File response, int id) {
                        //差量更新
                        fixedRex();

                    }
                });
    }

    public void jmp(View view){
//         int a = 1 / 0;
//
//        if (index%3==0){
            skipOtherActivity(PayActivity.class,false);
//        }else {
//            String versionCode = getVersionName();
//            ToastMake.showToast("当前的版本是"+versionCode);
//            System.out.println("当前的版本是"+versionCode);
//        }
//        ++index;

        //        ToastMake.showToast("暂时不能跳转");

    }


    private void fixedRex() {
        File patchFile = new File(Constants.PATCH_PATH);

        System.out.println("动态更新的文件路径是"+patchFile.getAbsolutePath());
        if (!ApkUtils.isInstalled(MainActivity.this, getPackageName())) {
            //            1.先安装WeiboV5.5（已通过云盘共享）

            System.out.println("需要先安装Apk");
//                        Toast.makeText(context, getString(R.string.demo_info1), Toast.LENGTH_LONG).show();
        } else if (!patchFile.exists()) {
            //            Toast.makeText(context, getString(R.string.demo_info2), Toast.LENGTH_LONG).show();
            //            2.将由服务器端生成的差分文件 weibo.patch（V5.5->V5.6）拷贝至：/sdcard/weibo.patch（已通过云盘共享）
            System.out.println("找不到NaXiang.patch文件");
        } else {
            new PatchApkTask().execute();
        }
    }

    private class PatchApkTask extends AsyncTask<String, Void, Integer> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(String... params) {
            PackageInfo packageInfo = ApkUtils.getInstalledApkPackageInfo(MainActivity.this, getPackageName());
            if (packageInfo != null) {

                requestOldMD5(packageInfo.versionCode, packageInfo.versionName);

                String oldApkSource = ApkUtils.getSourceApkPath(MainActivity.this, getPackageName());

                if (!TextUtils.isEmpty(oldApkSource)) {

                    // 校验一下本地安装APK的MD5是不是和真实的MD5一致
                    if (SignUtils.checkMd5(oldApkSource, mCurentRealMD5)) {
                        int patchResult = PatchUtils.patch(oldApkSource, Constants.NEW_APK_PATH, Constants.PATCH_PATH);

                        if (patchResult == 0) {

                            if (SignUtils.checkMd5(Constants.NEW_APK_PATH, mNewRealMD5)) {
                                return WHAT_SUCCESS;
                            } else {
                                return WHAT_FAIL_GEN_MD5;
                            }
                        } else {
                            return WHAT_FAIL_PATCH;
                        }
                    } else {
                        return WHAT_FAIL_OLD_MD5;
                    }
                } else {
                    return WHAT_FAIL_GET_SOURCE;
                }
            } else {
                return WHAT_FAIL_UNKNOWN;
            }
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);

            System.out.println("运行结果是"+result);
            switch (result) {

                case WHAT_SUCCESS: {
                    String text = "新apk已合成成功：" + Constants.NEW_APK_PATH;
                    ApkUtils.installApk(MainActivity.this, Constants.NEW_APK_PATH);
                    break;
                }
                case WHAT_FAIL_OLD_MD5: {
                    String text = "现在安装的WeiboV5.5的MD5不对！";
                    break;
                }
                case WHAT_FAIL_GEN_MD5: {
                    String text = "合成完毕，但是合成得到的apk MD5不对！";
                    break;
                }
                case WHAT_FAIL_PATCH: {
                    String text = "新apk已合成失败！";

                    break;
                }
                case WHAT_FAIL_GET_SOURCE: {
                    String text = "无法获取微博客户端的源apk文件，只能整包更新了！";
                    break;
                }
            }
        }


        /**
         * 模拟请求服务器，根据当前安装微博客户端的versionCode、versionName，来获取其文件的正确MD5，防止本地安装的是被篡改的版本
         */

        private String mCurentRealMD5, mNewRealMD5;
        private void requestOldMD5(int versionCode, String versionName) {
            mCurentRealMD5 = Constants.WEIBO_OLD_MD5;
            mNewRealMD5 = Constants.WEIBO_NEW_MD5;
        }
    }
    public void banner(View view){

        skipOtherActivity(BannerActivity.class,false);

//        startActivity(new Intent(MainActivity.this, BannerActivity.class));
    }

    public void absctract(View view){
        skipOtherActivity(NewBasicTextActivity.class,false);
    }

    public void pushjiguang(View view){

        startActivity(new Intent(MainActivity.this,JiGuangPoushActivity.class));
//        skipOtherActivity(JiGuangPoushActivity.class,false);
    }
}
